<?php
namespace app\middleware;

use app\common\traits\JumpTrait;
use app\common\services\AuthService;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;
use think\facade\Db; //数据库类
use ReflectionClass;

class RsAuth implements MiddlewareInterface
{
    use JumpTrait;
    public function process(Request $request, callable $handler) : Response
    {
        
        // 通过反射获取控制器哪些方法不需要登录
        $controller = new ReflectionClass($request->controller);
        $noNeedLogin = $controller->getDefaultProperties()['noNeedLogin'] ?? [];

        // 访问的方法需要登录
        
        if (!in_array($request->action, $noNeedLogin)) {
            // 拦截请求，返回一个重定向响应，请求停止向洋葱芯穿越
            $request = request();$session = $request->session();
            
            $session->put(['redirect_url' => $request->fullUrl()]);
            
            if(!session('uid')){
                $session->forget(['uid', 'name','key']);
                return $this->responseView('请登录1', [], '/login/login');
            }
            $ls = Db::name('user')->where(['id'=>session('uid')])->find();
            if(!$ls){
                $session->forget(['uid', 'name','key']);
                return $this->responseView('请登录2', [], '/login/login');
            }
            $ip = $request->getRemoteIp();
            if(session('uid') and $ip){
                if($ip != $ls['ip']){
                    $session->forget(['uid', 'name','key']);
                    return $this->responseView('登录IP有变化，请重新登录', [], '/login/login');
                }
            }
            if($ls['pw'] != session('key')){
                $session->forget(['uid', 'name','key']);
                return $this->responseView('密码已修改，请重新登录', [], '/login/login');
            }
            
        }

        // 不需要登录，请求继续向洋葱芯穿越
        return $handler($request);
    }
    
    

}